package com.tc.security.browser;

import com.tc.security.browser.session.TcExpiredSessionStrategy;
import com.tc.security.core.authentication.FormAuthenticationConfig;
import com.tc.security.core.authentication.mobile.SmsCodeAuthenticationSecurityConfig;
import com.tc.security.core.properties.SecurityConstants;
import com.tc.security.core.properties.SecurityProperties;
import com.tc.security.core.validate.code.SmsCodeFilter;
import com.tc.security.core.validate.code.ValidateCodeFilter;
import com.tc.security.core.validate.code.ValidateCodeSecurityConfig;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.util.Assert;

import javax.sql.DataSource;

/**
 * @Auther: tianchao
 * @Date: 2020/6/23 21:02
 * @Description:
 */
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    @Qualifier(value = "tcAuthenticationSuccessHandler")
    private AuthenticationSuccessHandler tcAuthenticationSuccessHandler;

    @Autowired
    @Qualifier(value = "tcAuthenticationFailureHandler")
    private AuthenticationFailureHandler tcAuthenticationFailureHandler;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;

    @Autowired
    private FormAuthenticationConfig formAuthenticationConfig;

    @Autowired
    private ValidateCodeSecurityConfig validateCodeSecurityConfig;

    @Autowired
    private InvalidSessionStrategy invalidSessionStrategy;

    @Autowired
    private SessionInformationExpiredStrategy sessionInformationExpiredStrategy;

    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;

    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        Assert.notNull(dataSource, "启用记住我功能后,数据源必须存在");
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        //tokenRepository.setCreateTableOnStartup(true);
        return tokenRepository;
    }


    /**
     * spring-security流程配置
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
        //validateCodeFilter.setTcAuthenticationFailureHandler(tcAuthenticationFailureHandler);
        //validateCodeFilter.setSecurityProperties(securityProperties);
        //validateCodeFilter.afterPropertiesSet();
//
        //SmsCodeFilter smsCodeFilter = new SmsCodeFilter();
        //smsCodeFilter.setTcAuthenticationFailureHandler(tcAuthenticationFailureHandler);
        //smsCodeFilter.setSecurityProperties(securityProperties);
        //smsCodeFilter.afterPropertiesSet();
//
        //表单登录配置
        formAuthenticationConfig.configure(http);

        http.apply(validateCodeSecurityConfig)
            .and()
                //记住我配置，如果想在'记住我'登录时记录日志，可以注册一个InteractiveAuthenticationSuccessEvent事件的监听器
            .rememberMe()
                .tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(securityProperties.getBrowser().getRememberMeSeconds())
                .userDetailsService(userDetailsService)
                .and()
            .sessionManagement()
                .invalidSessionStrategy(invalidSessionStrategy)
                .invalidSessionUrl("/session/invalid")
                .maximumSessions(securityProperties.getBrowser().getSession().getMaximumSessions())
                .maxSessionsPreventsLogin(securityProperties.getBrowser().getSession().isMaxSessionsPreventsLogin())
                .expiredSessionStrategy(sessionInformationExpiredStrategy)
                .and()
                .and()
             .logout()
                .logoutUrl("/signOut")
                .logoutSuccessHandler(logoutSuccessHandler)
                .deleteCookies("JSESSIONID")
                .and()
            .authorizeRequests()
                .antMatchers(
                    SecurityConstants.DEFAULT_UNAUTHENTICATION_URL,
                    SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_MOBILE,
                        securityProperties.getBrowser().getLoginPage(),
                        SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/*",
                        securityProperties.getBrowser().getSession().getSessionInvalidUrl(),
                        securityProperties.getBrowser().getLogoutPage(),
                        "/error","/user/session"
                )
                .permitAll()
                .anyRequest()
                .authenticated()
            .and()
            .csrf().disable()
            .apply(smsCodeAuthenticationSecurityConfig);

    }

}
